package com.tx.admin.util.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import com.tx.admin.util.common.DateUtil;
import com.tx.admin.util.common.UUIDUtils;

public class RespUtil {
	
	public static ResponseEntity<byte[]> downloadFile(String name,byte[] bytes){
	     HttpHeaders headers = new HttpHeaders(); 
	          
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);    	 
	        headers.setContentDispositionFormData("attachment", name);   
	  
			return new ResponseEntity<byte[]>(bytes,    headers, HttpStatus.CREATED);
	
	}
	
	public static ResponseEntity<byte[]> downloadFile(Workbook workbook) throws IOException{
		String name = DateUtil.getNowDateString()+".xlsx";
		ByteArrayOutputStream out = new ByteArrayOutputStream();
	        	// workbook写入ByteArrayOutputStream进行转化
        workbook.write(out);
        return downloadFile(name,out.toByteArray());

	}
	


	 public static void writeJson(HttpServletResponse response,Object obj) {
	        PrintWriter out = null;
	        try {
	        	String json;
	            response.setCharacterEncoding("UTF-8");
	            response.setContentType("application/json; charset=utf-8");
	            out = response.getWriter();
	            json=JsonUtil.toJson(obj);
	            out.write(json); 
	            out.flush();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	        	if(out != null) {
	        	    out.close();
	        	}
	           
	        }
	    }
	 /**
	  * 输出图片
	  * @param response
	  * @param image
	 * @throws IOException 
	  */
	public static void writeImage(HttpServletResponse response,BufferedImage  image) {
				response.setDateHeader("Expires", 0);  
		        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
		        response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
		        response.setHeader("Pragma", "no-cache");  
		        response.setContentType("image/jpeg");  
		        ServletOutputStream out=null;
				try {
					out = response.getOutputStream();
					ImageIO.write(image, "JPEG", out);
				    out.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					try {
						if(out != null) {
							out.close();
						}
					
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			
		}

}
